<template>
  <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
    <div class="about">
      <a-space direction="horizontal" :size="16" style="margin-bottom: 16px;">
        <a-input-search
            v-model:value="searchKeyword"
            placeholder="请搜索"
            enter-button="搜索"
            @search="handleSearch"
        />
        <a-button type="primary" @click="addJob">
          新增
        </a-button>
      </a-space>
      <a-table :columns="columns" :row-key="item => item.jobId" :data-source="jobs" :pagination="pagination"
               :loading="isLoading" @change="handleTableChange">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'salary_range'">
            <span>{{ record.salaryRange }}</span>
          </template>
          <template v-if="column.dataIndex === 'experience_required'">
            <span>{{ record.experienceRequired }}</span>
          </template>
          <template v-if="column.dataIndex === 'education_required'">
            <span>{{ record.educationRequired }}</span>
          </template>
          <template v-if="column.dataIndex === 'job_type'">
            <span>{{ record.jobType }}</span>
          </template>
          <template v-if="column.dataIndex === 'status'">
            <span>{{ record.status }}</span>
          </template>
          <template v-if="column.dataIndex === 'created_at'">
            <span>{{ formatDate(record.createdAt) }}</span>
          </template>
          <template v-if="column.dataIndex === 'updated_at'">
            <span>{{ formatDate(record.updatedAt) }}</span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-space size="small">
              <a-button type="primary"
                        @click="showModal(record)"
              >
                编辑
              </a-button>
              <a-popconfirm
                  title="是否确认要删除?"
                  ok-text="Yes"
                  cancel-text="No"
                  @confirm="deleteJob(record)"
              >
                <a-button danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </a-layout-content>
  <!-- 模态框 更新-->
  <a-modal v-model:open="open" title="编辑职位" :confirm-loading="confirmLoading" @ok="handleOk">
    <a-form ref="editForm" :model="JobDis" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" >
      <a-form-item label="职位标题" name="jobTitle">
        <a-input v-model:value="JobDis.title" />
      </a-form-item>
      <a-form-item label="公司ID" name="companyId">
        <a-input v-model:value="JobDis.companyId" />
      </a-form-item>
      <a-form-item label="描述" name="description">
        <a-textarea v-model:value="JobDis.description" />
      </a-form-item>
      <a-form-item label="薪资范围" name="salaryRange">
        <a-input v-model:value="JobDis.salaryRange" />
      </a-form-item>
      <a-form-item label="地点" name="location">
        <a-input v-model:value="JobDis.location" />
      </a-form-item>
      <a-form-item label="所需经验" name="experienceRequired">
        <a-input v-model:value="JobDis.experienceRequired" />
      </a-form-item>
      <a-form-item label="所需教育" name="educationRequired">
        <a-input v-model:value="JobDis.educationRequired" />
      </a-form-item>
      <a-form-item label="职位类型" name="jobType">
        <a-select v-model:value="JobDis.jobType" style="width: 100%">
          <a-select-option value="full_time">全职</a-select-option>
          <a-select-option value="part_time">兼职</a-select-option>
          <a-select-option value="remote">远程</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-select v-model:value="JobDis.status" style="width: 100%">
          <a-select-option value="active">活跃</a-select-option>
          <a-select-option value="closed">关闭</a-select-option>
          <a-select-option value="draft">草稿</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="创建时间">
        <a-date-picker v-model:value="JobDis.createdAt" show-time format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
      <a-form-item label="更新时间">
        <a-date-picker v-model:value="JobDis.updatedAt" show-time format="YYYY-MM-DD HH:mm:ss" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import axios from 'axios';
import dayjs from 'dayjs'; // 使用 dayjs 库来格式化日期
import { message } from 'ant-design-vue';
/* eslint-disable */
const open = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
// 表格数据
const jobs = ref<Job[]>([]);
interface Pagination {
  current: number;
  pageSize: number;
  total?: number;
  [key: string]: any; // 可选扩展字段
}

// 分页信息
const pagination = ref({
  pageSize: 10, // 设置每页显示10条数据
  total: 0,
  current: 1
});
// 数据加载状态
const isLoading = ref(true);
// 搜索关键字
const searchKeyword = ref<string>('');
// 是否搜索状态
const isSearch = ref(false);
// 日期格式化函数
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};
// 表格分页逻辑
const handleTableChange = (pag: Pagination) => {
  pagination.value.current = pag.current;
  pagination.value.pageSize = pag.pageSize;
  if (!isSearch.value) {
    fetchJobs();
  } else {
    handleSearch();
  }
  window.scrollTo({ top: 0, behavior: 'smooth' });
};
// 获取职位列表
const fetchJobs = async () => {
  try {
    isLoading.value = true;
    const res = await axios.get('/jobs/list', {
      params: {
        page: pagination.value.current,
        size: pagination.value.pageSize
      }
    });
    isLoading.value = false;
    pagination.value.total = res.data.data.total;
    jobs.value = res.data.data.list;
    console.log('Fetched jobs:', jobs.value);
    if (jobs.value.length === 0 && pagination.value.current > 1) {
      pagination.value.current = pagination.value.current - 1;
      fetchJobs();
    }
  } catch (err) {
    console.error('请求失败:', err);
    isLoading.value = false;
  }
};

// 显示修改弹窗
const showModal = (record: Job) => {
  if (record) {
    open.value = true;
    JobDis.value = {
      jobId: record.jobId,
      title: record.title,
      companyId: record.companyId,
      description: record.description,
      salaryRange: record.salaryRange,
      location: record.location,
      experienceRequired: record.experienceRequired,
      educationRequired: record.educationRequired,
      jobType: record.jobType,
      status: record.status,
      createdAt: dayjs(record.createdAt),
      updatedAt: record.updatedAt ? dayjs(record.updatedAt) : undefined, // 修改为 undefined 如果没有更新时间
    };
    console.log('record:', record);
  } else {
    console.error('Invalid record passed to showModal:', record);
  }
};
const addJob = () => {
  open.value = true;
  JobDis.value = {
    jobId: 0,
    title: '',
    companyId: undefined,
    description: '',
    salaryRange: '',
    location: '',
    experienceRequired: '',
    educationRequired: '',
    jobType: 'full_time',
    status: 'draft',
    createdAt: '',
    updatedAt: undefined, // 修改为 undefined
  };
};
const handleOk = () => {
    if(JobDis.value.jobId === 0){
      doAddJob()
    }else{
      updateJob()
    }
};
const doAddJob = () => {
    confirmLoading.value = true;
    setTimeout(() => {
      open.value = false;
      confirmLoading.value = false;
    }, 500);
    axios.post('/jobs/add', {
      title: JobDis.value.title,
      companyId: JobDis.value.companyId,
      description: JobDis.value.description,
      salaryRange: JobDis.value.salaryRange,
      location: JobDis.value.location,
      experienceRequired: JobDis.value.experienceRequired,
      educationRequired: JobDis.value.educationRequired,
      jobType: JobDis.value.jobType,
      status: JobDis.value.status,
      createdAt: JobDis.value.createdAt ? JobDis.value.createdAt : '',
      updatedAt: JobDis.value.updatedAt ? JobDis.value.updatedAt : '',
    }).then(res => {
      if (res.data.code === 200) {
        JobDis.value = {
          jobId: 0,
          title: '',
          companyId: undefined,
          description: '',
          salaryRange: '',
          location: '',
          experienceRequired: '',
          educationRequired: '',
          jobType: 'full_time',
          status: 'draft',
          createdAt: '',
          updatedAt: undefined, // 修改为 undefined
        };
        if (!isSearch.value) {
          fetchJobs();
        }else {
          handleSearch();
        }
        message.success('添加职位成功');
      }
    }).catch(() => {
      message.error('添加职位失败，请稍后重试');
    });
};
const updateJob = () => {
  confirmLoading.value = true;
  setTimeout(() => {
    open.value = false;
    confirmLoading.value = false;
  }, 500);
  console.log("1234"+JobDis.value);
  axios.post('/jobs/update', {
    jobId: JobDis.value.jobId,
    title: JobDis.value.title,
    description: JobDis.value.description,
    salaryRange: JobDis.value.salaryRange,
    location: JobDis.value.location,
    companyId: JobDis.value.companyId,
    experienceRequired: JobDis.value.experienceRequired,
    educationRequired: JobDis.value.educationRequired,
    jobType: JobDis.value.jobType,
    status: JobDis.value.status,
    createdAt: formatDate(JobDis.value.createdAt),
    updatedAt: JobDis.value.updatedAt ? formatDate(JobDis.value.updatedAt) : undefined,
  }).then(res => {
    JobDis.value = {
      jobId: 0,
      title: '',
      companyId: undefined,
      description: '',
      salaryRange: '',
      location: '',
      experienceRequired: '',
      educationRequired: '',
      jobType: 'full_time',
      status: 'draft',
      createdAt: '',
      updatedAt: undefined, // 修改为 undefined
    };
    if (!isSearch.value) {
      fetchJobs();
    } else {
      handleSearch();
    }
    if(res.data.code === 200){
      message.success('更新职位信息成功');
    }else {
      message.error('更新职位信息失败');
    }
  }).catch(err => {
    console.error('更新职位失败:', err);
    message.error('更新职位失败，请稍后重试');
  });
};

// 搜索逻辑
const handleSearch = () => {
  isLoading.value = true;
  console.log('搜索职位信息:', searchKeyword.value);
  axios.post('/jobs/query', {
    title: searchKeyword.value,
  }).then(res => {
    if (res.data.code === 200) {
      isSearch.value = true;
      pagination.value.total = res.data.data.total;
      jobs.value = res.data.data;
      console.log('res.data.data', res.data.data);
      console.log('res.data.data.list', res.data.data.list);
      isLoading.value = false;
      message.success('搜索职位信息成功');
    }else{
      message.error('搜索失败')
    }
  }).catch(err => {
    console.error('搜索失败:', err);
    isLoading.value = false;
  });
};

// 删除职位
const deleteJob = (record: Job) => {
  axios.post('/jobs/delete', {
    jobId: record.jobId
  }).then(() => {
    if (!isSearch.value) {
      fetchJobs();
    }
    if (jobs.value.length === 0) {
      pagination.value.current = pagination.value.current - 1;
      handleSearch();
    }
    if(isSearch.value){
      handleSearch();
    }
    message.success('删除职位信息成功');
  }).catch(() => {
    message.error('删除职位失败，请稍后重试');
  });
};

// 定义职位数据的类型
interface Job {
  jobId: number;
  title: string;
  companyId: number | undefined;
  description: string;
  salaryRange: string;
  location: string;
  experienceRequired: string;
  educationRequired: string;
  jobType: 'full_time' | 'part_time' | 'remote';
  status: 'active' | 'closed' | 'draft';
  createdAt: string;
  updatedAt: string | undefined; // 修改为 string | undefined
}
// 初始化 JobDis 为一个空对象
const JobDis = ref<Job>({
  jobId: 0,
  title: '',
  companyId: 0,
  description: '',
  salaryRange: '',
  location: '',
  experienceRequired: '',
  educationRequired: '',
  jobType: 'full_time',
  status: 'draft',
  createdAt: '',
  updatedAt: undefined, // 修改为 undefined
});
// 定义表格结构
const columns = [
  {
    title: '职位标题',
    dataIndex: 'title',
  },
  {
    title: '公司ID',
    dataIndex: 'companyId',
  },
  {
    title: '描述',
    dataIndex: 'description',
  },
  {
    title: '薪资范围',
    dataIndex: 'salaryRange',
  },
  {
    title: '地点',
    dataIndex: 'location',
  },
  {
    title: '所需经验',
    dataIndex: 'experienceRequired',
  },
  {
    title: '所需教育',
    dataIndex: 'educationRequired',
  },
  {
    title: '职位类型',
    dataIndex: 'jobType',
  },
  {
    title: '状态',
    dataIndex: 'status',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
  },
  {
    title: '更新时间',
    dataIndex: 'updatedAt',
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center' as const, // 对齐方式
    width: 150,
    // fixed: 'right' // 固定在右侧
  }
];
onMounted(async () => {
  await fetchJobs();
});
</script>
